<template>
  <h2>组合api</h2>
  <button @click="decrement">-</button>
  <span>{{ count }}</span>
  <button @click="increment">+</button>

  <hr />

  <input type="text" v-model="value" />
  <button @click="add">添加</button>
  <ul>
    <li v-for="item in list" :key="item">
      {{ item }} - <button @click="remove(item)">删除</button>
    </li>
  </ul>
</template>

<script>
// ref是用来创建响应式变量的
import { ref } from "vue";
import useCount from "./utils/useCount";

export default {
  // setup是组合api的入口
  // setup理解为一个特殊的生命周期
  // 有了setup函数以后，其他的选项都可以不用写了，也可以写
  // setup里面是没有this的
  setup() {
    const [count, increment, decrement] = useCount();
    const [value, list, add, remove] = useList();

    // return是将变量暴露给tempalte
    return { count, increment, decrement, value, list, add, remove };
  },
};

const useList = () => {
  const value = ref("");
  const list = ref(["张三", "李四"]);
  const add = () => {
    list.value.push(value.value);
    value.value = "";
  };
  const remove = (name) => {
    list.value = list.value.filter((item) => item !== name);
  };

  return [value, list, add, remove];
};
</script>
